<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item v-if="this.$route.query.referrer==0" label="邀请人" prop="referrer">
        <el-input
          v-model="queryParams.referrer"
          placeholder="请输入邀请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员类型" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择会员类型" clearable>
          <el-option
            v-for="dict in dict.type.novel_vip_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择注册时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['novel:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['novel:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['novel:user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['novel:user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="邀请人" align="center" prop="referrerName" />
      <el-table-column label="昵称" align="center" prop="nickName" />
      <el-table-column label="头像" align="center" prop="avatarUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatarUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="余额" align="center" prop="money" />
      <el-table-column label="会员类型" align="center" prop="level">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.novel_vip_type" :value="scope.row.level"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.novel_user_role" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="getIntegralList(scope.row)"
            v-hasPermi="['novel:user:edit']"
          >充值</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="getVipList(scope.row)"
            v-hasPermi="['novel:user:edit']"
          >会员</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['novel:user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['novel:user:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['novel:user:edit']"
          >重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatarUrl">
          <image-upload v-model="form.avatarUrl" :limit="1"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.novel_user_role"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分成比例" prop="commission" v-if="form.state==1">
          <el-input-number v-model="form.commission" :min="0" :max="getUserCeng()" :step="0.01" :precision="2" label="描述文字"></el-input-number>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="integralList.length > 0" width="1000px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="积分" prop="state">
          <el-select v-model="form.integralId" placeholder="请选择充值积分">
            <el-option
              v-for="dict in integralList"
              :key="dict.id"
              :label="dict.title"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="vipList.length > 0" width="1000px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员" prop="state">
          <el-select v-model="form.vipId" placeholder="请选择开通会员">
            <el-option
              v-for="dict in vipList"
              :key="dict.id"
              :label="dict.title"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, userRecharge } from "@/api/novel/user";
import { resetUserPwd } from "@/api/system/user";
import { listIntegral } from "@/api/novel/integral";
import { listVip } from "@/api/novel/vip";

export default {
  name: "User",
  dicts: ['novel_vip_type', 'novel_state', 'novel_user_role'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        referrer: null,
        phone: null,
        level: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      //邀请人信息
      referrer: null,
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "昵称不能为空", trigger: "blur" }
        ],
        avatarUrl: [
          { required: true, message: "头像不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
      },

      integralList: [],
      vipList: [],
      roles: [],
    };
  },
  created() {
    // console.log(this.$store.state.user.roles)
    // this.roles = this.$store.state.user.roles;
    this.getList();
  },
  methods: {
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.nickName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
        resetUserPwd(row.id, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {});
    },
    getUserCeng(){
      if(this.referrer){
        return this.referrer.commission
      }
      return 0.9;
    },
    /** 查询积分商品列表 */
    getIntegralList(row) {
      listIntegral({
        pageNum: 1,
        pageSize: 1000,
      }).then(response => {
        this.integralList = response.rows;
        this.form = row;
        this.form.mode = 1;
      });
    },
    /** 查询会员商品列表 */
    getVipList(row) {
      listVip({
        pageNum: 1,
        pageSize: 1000,
      }).then(response => {
        this.vipList = response.rows;
        this.form = row;
        this.form.mode = 0;
      });
    },
    /** 查询用户信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.referrer = this.$route.query.referrer==1?1:null;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.integralList = [];
      this.vipList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vipId: null,
        integralId: null,
        referrer: null,
        openId: null,
        nickName: null,
        avatarUrl: null,
        phone: null,
        money: null,
        level: null,
        mode: null,
        commission: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
      if(this.$route.query.referrer==1){
        this.form.state = 1;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.referrer = response.referrer;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if(this.form.mode == null){
              updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }else {
              userRecharge(this.form).then(response => {
                this.$modal.msgSuccess(response.msg);
                this.cancel();
                this.getList();
              });
            }
          } else {
            this.form.referrer = this.$route.query.referrer==1?1:null;
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功,默认账号密码均为手机号");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户信息编号为"' + ids + '"的数据项？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('novel/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
